#!/bin/bash

ROOT_PATH=$(cd $(dirname $0) && pwd);

PRX_IP=prx.geocat.space
USERS="user prx-client prz-client $(hostname)"
PASS=$(cat $ROOT_PATH/vpn_prx/user.secret)

VPN_NET=10.126.253
PRZ_GW=10.126.251.2

PRX_INET_HOSTS="trc01 dvv01"
PRX_HOSTS="trv01 trn01 dvn01"
PRX_KNOWN_HOSTS="$PRX_INET_HOSTS $PRX_HOSTS"


DEBS="strongswan strongswan-swanctl libstrongswan-extra-plugins libcharon-extra-plugins strongswan-pki"


sysctl net.ipv4.ip_forward=1
sysctl net.ipv6.conf.all.forwarding=1

if ! ( cat /etc/sysctl.conf | grep -q "#_#net.ipv4.ip_forward" )
then

sudo sed -i 's/^#net.ipv4.ip_forward/#_#net.ipv4.ip_forward/' /etc/sysctl.conf
sudo sed -i 's/^net.ipv4.ip_forward/#_#net.ipv4.ip_forward/' /etc/sysctl.conf
sudo sed -i '1i\net.ipv4.ip_forward = 1' /etc/sysctl.conf

sudo sed -i 's/^net.ipv6.conf.all.forwarding/#_#net.ipv6.conf.all.forwarding/' /etc/sysctl.conf
sudo sed -i '1i\net.ipv6.conf.all.forwarding = 1' /etc/sysctl.conf

fi


if [ -f "/etc/NetworkManager/NetworkManager.conf" ] && ! ( cat /etc/NetworkManager/NetworkManager.conf | grep -q -x "dns=none" )
then

sudo sed -i 's/^dns=/#_#dns=/' /etc/NetworkManager/NetworkManager.conf
#sudo sed -i '2i\dns=default' /etc/NetworkManager/NetworkManager.conf
sudo sed -i '2i\dns=none' /etc/NetworkManager/NetworkManager.conf

sudo systemctl restart NetworkManager

#sudo systemctl stop systemd-resolved
#sudo systemctl disable systemd-resolved
#sudo rm -f /etc/resolv.conf

apt -y install resolvconf
sudo systemctl enable systemd-resolved
sudo systemctl start systemd-resolved

fi


#if [ -f /usr/local/bin/vpn.sh ]
#then
#	unset FIRST_INSTALL
#else
#	apt -y purge $DEBS
#	apt autopurge -y
#fi

apt -y install $DEBS


sudo sh -c "echo '
conn %default
 ike=aes256-aes128-sha256-sha1-modp2048-modp4096-modp1024,3des-sha1-modp1024
 esp=aes128-aes256-sha1-sha256-modp2048-modp4096-modp1024,aes128-sha1-modp2048,aes128-sha1-modp1024,3des-sha1-modp1024,aes128-aes256-sha1-sha256,aes128-sha1,3des-sha1
 keyexchange=ikev1
 left=%defaultroute
 leftsourceip=%config
 leftfirewall=yes
 leftauth=psk
 leftauth2=xauth
 right='$PRX_IP'
 rightauth=psk
 auto=add
 rightid=%any
' > /etc/ipsec.conf"

sudo sh -c "echo '
conn prz
 #leftdns='$PRZ_GW'
 #leftdns=%config
 leftdns='$VPN_NET'.1
 #leftdns=8.8.8.8,8.8.4.4
 #leftsubnet='$VPN_NET'.0/24
 leftid=prz-client
 rightsubnet=0.0.0.0/0
 #rightsubnet='$VPN_NET'.0/24
' >> /etc/ipsec.conf"

sudo sh -c "echo '
conn prx
 leftdns='$VPN_NET'.1
 #leftdns=%config
 #leftdns=8.8.8.8,8.8.4.4
 #leftsubnet='$VPN_NET'.0/24
 leftid=prx-client
 #rightsubnet=0.0.0.0/0
 rightsubnet='$VPN_NET'.0/24
' >> /etc/ipsec.conf"

if ( echo "$PRX_KNOWN_HOSTS" | grep -q "$(hostname)" )
then
sudo sh -c "echo '
conn prx-inet
 leftdns='$VPN_NET'.1
 #leftdns=%config
 #leftdns=8.8.8.8,8.8.4.4
 #leftsubnet='$VPN_NET'.0/24
 leftid='$(hostname)'
 rightsubnet=0.0.0.0/0
 #rightsubnet='$VPN_NET'.0/24
' >> /etc/ipsec.conf"
fi

if [ ! -e "/etc/ipsec.secrets.bak" ]
then
sudo cp /etc/ipsec.secrets /etc/ipsec.secrets.bak
fi

sudo sed -i 's/^[^#].*//' /etc/ipsec.secrets

sudo sh -c "echo '
: PSK \"'$(cat $ROOT_PATH/vpn_prx/ipsec.secret)'\"
' >> /etc/ipsec.secrets"

for user in $USERS; do
sudo sh -c "echo $user' : XAUTH \"'$PASS'\"
' >> /etc/ipsec.secrets"
done

sudo sed -i '/^\s*$/d' /etc/ipsec.secrets

sudo ipsec restart

### VPN control scripts

sudo sh -c "echo '#! /bin/bash

NAME=vpn
DESC=\"VPN Starter\"
PIDFILE=/var/run/\$NAME.pid
LOGFILE=/var/log/\$NAME.log

echo === \$1 \$2 ===

case \"\$1\" in

keep)
	if ! \$0 is \$2
	then
		\$0 up \$2
	fi
;;

is)
    if [ -n \"\$2\" ]; then
		setsid ipsec start
		
		if [ -z \"\`swanctl -l | sed -n /\$2:/p\`\" ]; then
			exit 1
		else
			if ping -c 1 -W 1 $VPN_NET.1 ; then
				echo \$2
				exit 0
			else
				\$0 down
				exit 1
			fi
		fi
	else
		exit 1
	fi
;;

start)
	if [ -n \"\$2\" ]; then
		if \$0 status
		then
			echo already running
			exit 1
		else
			export TERM=linux
			PID=\`setsid watch \$0 keep \$2 < /dev/null > \$LOGFILE 2>&1 & echo \$!\`
			if [ -n \"\$PID\" ]; then
				echo \$PID > \$PIDFILE
				sleep 1
				if ! \$0 status
				then
					PID=\`setsid watch \$0 keep \$2 < /dev/null >> \$LOGFILE 2>&1 & echo \$!\`
				fi
			fi
			if [ -n \"\$PID\" ]; then
				echo \$PID > \$PIDFILE
				echo started \$PID
			else
				echo run error
				exit 1
			fi
		fi
	else
		echo no connection name to start
		exit 1
	fi
;;

stop)
        if [ -r \$PIDFILE ]; then
            PID=\`cat \$PIDFILE\`
            echo kill \$PID
            kill -HUP \$PID
            rm -f \$PIDFILE
        fi
        \$0 down
;;

status)
		if [ -r \$PIDFILE ]; then
            PID=\`cat \$PIDFILE\`
            if [ -z \"\`ps axf | grep \${PID} | grep -v grep\`\" ]; then
                rm -f \$PIDFILE
				#echo stopped
				exit 1
            else
                #echo running \$PID
                echo \$PID
            fi
        else
            #echo stopped
            exit 1
        fi
;;

restart)
    if [ -n \"\$2\" ]; then
		\$0 stop
		\$0 start \$2
	else
		exit 1
	fi
;;

up)
    if [ -n \"\$2\" ]; then
		setsid ipsec start
		#ipsec start
		setsid ipsec up \$2
	fi
;;

down)
	setsid ipsec start
    if [ -n \"\`swanctl -l\`\" ]; then
		if [ -n \"\$2\" ]; then
			#echo Down \$2
			setsid ipsec down \$2
		else
			#echo ipsec restart...
			#setsid ipsec restart
			#setsid ipsec stop
			#ipsec stop
			#echo Down All
			swanctl -l | sed -n /:/p |\\
				(
				  while IFS= read -r STR ; do
				  
					NAME=\$(echo \$STR | cut -s -d\":\" -f 1)
					
					if [ -n \"\$NAME\" ]; then
						\$0 down \$NAME
					fi

				  done
				)
		fi
	fi
;;

*)
        echo \"Usage: \$0 {status|start|stop|restart|keep|is|up|down} [connection_name]\"
        exit 1
esac

' > /usr/local/bin/vpn.sh"

sudo chmod a+x /usr/local/bin/vpn.sh

### VPN manual start

rm /usr/share/applications/Vpn*.desktop

sudo sh -c "echo '[Desktop Entry]
Type=Application
Name=VPN FAR UP
Exec=sh -c '\"'\"'pkexec vpn.sh restart prz'\"'\"'
Icon=swanctl
Terminal=true
' > /usr/share/applications/VpnFarUp.desktop"

sudo sh -c "echo '[Desktop Entry]
Type=Application
Name=VPN UP
Exec=sh -c '\"'\"'pkexec vpn.sh restart prx'\"'\"'
Icon=swanctl
Terminal=true
' > /usr/share/applications/VpnUp.desktop"

if ( echo "$PRX_KNOWN_HOSTS" | grep -q "$(hostname)" )
then
sudo sh -c "echo '[Desktop Entry]
Type=Application
Name=VPN INET UP
Exec=sh -c '\"'\"'pkexec vpn.sh restart prx-inet'\"'\"'
Icon=swanctl
Terminal=true
' > /usr/share/applications/VpnInetUp.desktop"
fi

sudo sh -c "echo '[Desktop Entry]
Type=Application
Name=VPN DOWN
Exec=sh -c '\"'\"'pkexec vpn.sh stop'\"'\"'
Icon=swanctl
Terminal=true
' > /usr/share/applications/VpnDown.desktop"

### VPN default start

if $(echo $PRX_HOSTS | grep -q $(hostname))
#if [[ "$PRX_HOSTS" =~ "$(hostname)" ]]
then

echo Add prx starter

sudo sh -c "echo '#! /bin/bash

VPN=prx

if [ -n \"\$1\" ]; then
	. vpn.sh \$1 \$VPN
else
	. vpn.sh restart \$VPN
fi

' > /usr/local/bin/vpn-start.sh"

sudo chmod a+x /usr/local/bin/vpn-start.sh

fi

if $(echo $PRX_INET_HOSTS | grep -q $(hostname))
#if [[ "$PRX_INET_HOSTS" =~ "$(hostname)" ]]
then


echo Add prx-inet starter

sudo sh -c "echo '#! /bin/bash

VPN=prx-inet

if [ -n \"\$1\" ]; then
	. vpn.sh \$1 \$VPN
else
	. vpn.sh restart \$VPN
fi

' > /usr/local/bin/vpn-start.sh"

sudo chmod a+x /usr/local/bin/vpn-start.sh

fi


if [ -x "/usr/local/bin/vpn-start.sh" ]
then


# Nightly VPN default restart

sudo sh -c "echo '#! /bin/bash

HOUR=\`eval date +%H\`

if [ \"\$HOUR\" = \"05\" ]; then
	. vpn-start.sh
fi

' > /etc/cron.hourly/vpn-nightly-restart"

sudo chmod a+x /etc/cron.hourly/vpn-nightly-restart


# On Lock VPN default restart

sudo sh -c "echo '#! /bin/bash

NAME=vpn-on-lock
DESC=\"On Lock Default VPN Starter\"
PIDFILE=/var/run/\$NAME.pid
LOGFILE=/var/log/\$NAME.log

case \"\$1\" in

watch)
	gdbus monitor -y -d org.freedesktop.login1 |\\
	(
	  while IFS= read -r STR ; do
	  
		case \$STR in

		  *\"login1.Session.Lock\"*)
			echo \$STR >> \$LOGFILE
			bash vpn-start.sh
			;;

		  *\"login1.Session.Unlock\"*)
			echo \$STR >> \$LOGFILE
			bash vpn.sh stop
			;;
			
		esac

	  done
	)
;;

start)
	if \$0 status
	then
		echo already running
		exit 1
	else
		export TERM=linux
		PID=\`setsid bash \$0 watch < /dev/null > /dev/null 2>&1 & echo \$!\`
		if [ -n \"\$PID\" ]; then
			echo \$PID > \$PIDFILE
			echo started \$PID | tee \$LOGFILE
		else
			echo run error
			exit 1
		fi
	fi
;;

stop)
        if [ -r \$PIDFILE ]; then
            PID=\`cat \$PIDFILE\`
            echo kill \$PID
            kill -HUP \$PID
            rm -f \$PIDFILE
        fi
;;

status)
		if [ -r \$PIDFILE ]; then
            PID=\`cat \$PIDFILE\`
            if [ -z \"\`ps axf | grep \${PID} | grep -v grep\`\" ]; then
                rm -f \$PIDFILE
				#echo stopped
				exit 1
            else
                #echo running \$PID
                echo \$PID
            fi
        else
            #echo stopped
            exit 1
        fi
;;

*)
        echo \"Usage: \$0 {start|stop|status|watch}\"
        exit 1
esac

' > /usr/local/bin/vpn-on-lock.sh"

sudo chmod a+x /usr/local/bin/vpn-on-lock.sh


### VPN boot start

sudo sh -c "echo '#! /bin/bash

### BEGIN INIT INFO
# Provides:          vpn
# Required-Start:    \$remote_fs
# Required-Stop:     
# Default-Start:     5
# Default-Stop:      
# Short-Description: start vpn
# Description:       start default vpn
### END INIT INFO

. vpn-start.sh \$1
. vpn-on-lock.sh \$1

' > /etc/init.d/vpn.sh"

sudo chmod a+x /etc/init.d/vpn.sh
sudo update-rc.d vpn.sh defaults


# Start default VPN

sudo bash vpn-start.sh
sudo bash vpn-on-lock.sh stop
sudo bash vpn-on-lock.sh start

else

	sudo rm /etc/cron.hourly/vpn-nightly-restart
	sudo rm /usr/local/bin/vpn-on-lock.sh
	sudo rm /etc/init.d/vpn.sh

fi
